﻿/**
 * @Description: 用户管理
 * @Author: Tom
 * @Date: 2020-01-09 10:39:55
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2020-04-07 16:15:12
 */

$(function () {
    var flag = "";
    // 重置窗口大小
    function resizeWindow() {
        var DEBUG;
        //DEBUG = true;
        if (DEBUG) {
            [].forEach.call($($('*')), function (a) {
                a.style.outline = '1px solid #' + (~~(Math.random() * (1 << 24))).toString(16);
            });
        }
        //console.log('resize...');
        var minHeight = $(window).height() - $('#dataTreeDiv').offset().top - 20;
        $('#dataTreeDiv').css('max-height', minHeight);
        $('.leftDiv').height($(window).height() - $('.leftDiv').offset().top - 20);
    }
    resizeWindow();
    // resize窗口
    window.onresize = function () {
        resizeWindow();
    };

    // 搜索
    $('.searchBtn').on('click', function () {
        getUserInfo('search');
    });

    // 根节点id(自定义)
    var rootNodeId = '101010';
    // 当前节点id
    var nowNodeId = '';
    // 当前节点对象
    var nowNode;
    // 当前页码
    var nowPage = 1;
    // 获取用户信息参数历史
    var getUserHis;
    var portaluserno = getCookie('portaluserno')
    var configInfo = InitialParameter("/Config.json")
    var modelApi = getBaseplatformPort() 
    var orgInputNewText

    function getUserInfo(id, page, isSecond, userId) {
        getUserHis = [id, page, isSecond];
        $('#userTable').html('');
        // var data = {
        //     hasTotal: 1, // 是否返回用户数据总条数: 1/0
        //     pageNum: page || 1, // 请求页码: 1,2,3…
        //     perPageNum: 10, // 每页条数: 1,2,3…
        // };
        let data = {}
        if (id == 'search') {
            data = {
                no: $('#searchUserName').val(),
                name: $('#searchName').val(),
                // orgId:userId ? userId : '101010' 
                orgId: nowNodeId
            }
        } else {
            data = {
                orgId: id ? id : '101010'
            }
        }
        // 查询相关机构的用户列表（分页） 
        $.ajax({
            type: "post",
            async: false,
            // url: "/BaseAshx/User/UserManage.ashx",
            // data: data,
            url: id == 'search' ? modelApi + 'user/getUserInfoByNames' : modelApi + 'user/getUserInfoByOrgID',
            data: data,
            datatype: "json",
            success: function (result) {
                result = JSON.parse(result);
                if (result.code == 200) {
                    if (!result.data) {
                        $('#userTable').html(`<div style="
                            height: 100px;
                            line-height: 100px;
                            text-align: center;
                            font-size: xx-large;
                            color: #666;">无数据</div>`);
                        $('#pagination').html('');
                        return;
                    }
                    // console.log(result);
                    var html = `
                    <tbody>
                    <tr class="head" align="center" style="cursor: default">
                            <th>用户名</th>
                            <th>中文名</th>
                            <th>所在部门</th>
                            <th>职务</th>
                            <th>手机号码</th>
                            <th>邮箱</th>
                            <th>部门管理员</th>
                        </tr>`;
                    result.data.map(function (item, index) {
                        if (item.TYPE == "1")
                            html += '<tr align="center" userId="' + item.USERID + '"><td>' + item.USERNAME + '</td><td>' + item.NAME + '</td><td departmentId="' + item.ORG_ID + '">' + item.DEPARTMENT + '</td><td>' + item.TITLE + '</td><td>' + item.PHONE + '</td><td>' + item.MAIL + '</td><td>是</td></tr>';
                        else
                            html += '<tr align="center" userId="' + item.USERID + '"><td>' + item.USERNAME + '</td><td>' + item.NAME + '</td><td departmentId="' + item.ORG_ID + '">' + item.DEPARTMENT + '</td><td>' + item.TITLE + '</td><td>' + item.PHONE + '</td><td>' + item.MAIL + '</td><td>否</td></tr>';
                    });
                    html += '</tbody>';
                    $('#userTable').html(html);
                    // $('#tableTitleDiv table').append(html);
                    var data = {
                        pageTotal: Math.ceil(result.data.total / 10),
                        pageAmount: 10, // 每页多少条
                        dataTotal: result.data.total,
                        curPage: 1
                    };
                    if (isSecond) {
                        return;
                    }
                    new Page({
                        id: 'pagination',
                        pageTotal: data.pageTotal, //必填,总页数（最少1页）
                        pageAmount: data.pageAmount, //每页多少条
                        dataTotal: data.dataTotal, //总共多少条数据（至少1条）
                        curPage: data.curPage, //初始页码,不填默认为1
                        pageSize: data.pageSize, //分页个数,不填默认为5
                        showPageTotalFlag: true, //是否显示数据统计,不填默认不显示
                        showSkipInputFlag: true, //是否支持跳转,不填默认不显示
                        getPage: function (page) {
                            nowPage = page;
                            // 请求数据
                            if (id == 'search') {
                                getUserInfo('search', page, true, nowNodeId);
                            } else {
                                getUserInfo(nowNodeId, page, true);
                            }
                        }
                    });
                    nowPage = 1;
                } else {
                    layui.layer.msg(result.msg, {
                        shade: 0.3,
                        time: 1000 // 1秒关闭
                    });
                    return;
                }
            },
            error: function (err) {
                console.log(err);
                var msg = '';
                if (err.status == 405) {
                    msg = '未登录, 请先登录';
                    setTimeout(function () {
                        top.location.href = '/';
                    }, 500);
                } else {
                    msg = '数据获取失败';
                }
                layui.layer.msg(msg, {
                    shade: 0.3,
                    time: 1000 // 1秒关闭
                });
            }
        });
    }
    // 初始化右侧
    getUserInfo(nowNodeId);
    var addBranchType = false 
    var adType = false 

    // 选中用户
    $('#userTable').on('click', 'tr', function (e) { 
        addBranchType = true   
        adType = false 
        $('.addBtn').addClass('unable')
        var $currentTarget = $(e.currentTarget); 
        if (!$currentTarget.hasClass('head')) {
            if ($currentTarget.hasClass('curSelectedNode')) {
                $currentTarget.removeClass('curSelectedNode');
            } else {
                $('#userTable .curSelectedNode').removeClass('curSelectedNode');
                $currentTarget.addClass('curSelectedNode');
            }
        } else {}
        if ($('#userTable .curSelectedNode').length) {
            $('.editBtn, .deleteBtn, .resetPassWordBtn').removeClass('unable');   
        } else {
            $('.editBtn, .deleteBtn, .resetPassWordBtn').addClass('unable');
        }
    });
    
    // 新建用户
    $('.addBtn').on('click', function () {
        if (addBranchType && adType) {
            flag = "isAdd";
            var html = `
    <div class = "layui-form">
        <div class="layui-form-item">
                        <label class="layui-form-label">用户名：</label>
                        <div class="layui-input-block">
                            <input id="userNameInput" type="text"  autocomplete="new-password"  placeholder="请输入用户名" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">中文名：</label>
                        <div class="layui-input-block">
                            <input id="fullNameInput" type="text"  autocomplete="new-password"  placeholder="请输入中文名" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">所在部门：</label>
                        <div class="layui-input-block">
                            <select id="orgInput"></select>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">职务：</label>
                        <div class="layui-input-block">
                            <input id="titleInput" type="text"  autocomplete="new-password"  placeholder="请输入职务" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">手机号码：</label>
                        <div class="layui-input-block">
                            <input id="phoneInput" type="text"  autocomplete="new-password"  placeholder="请输入手机号码" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">邮箱：</label>
                        <div class="layui-input-block">
                            <input id="mailInput" type="text"  autocomplete="new-password"  placeholder="请输入邮箱" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">密码：</label>
                        <div class="layui-input-block">
                            <input id="pwdInput" type="password" autocomplete="off"  placeholder="请输入密码" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">确认密码：</label>
                        <div class="layui-input-block">
                            <input id="rePwdInput" type="password" autocomplete="off"  placeholder="请确认密码" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">部门管理员：</label>
                        <div class="layui-input-block">
                            <input id="isManagerInput" type="checkbox">
                        </div>
                    </div>
    </div>
    `;
            $('#orgInput').on('focus', function () {
                if ($('#ztreeDiv').is(':hidden')) {
                    $('#ztreeDiv').show()
                    var top = $('#orgInput').offset().top + $('#orgInput').height() + 3;
                    var left = $('#orgInput').offset().left;
                    $('#ztreeDiv').show().css({
                        top: top,
                        left: left
                    });
                }
            })
            let type = false
            $('#orgInputNew').val(orgInputNewText)
            var content = '<div>' + html + '</div>';
            $('#userNameInput').val("");
            $('#fullNameInput').val("");
            $('#orgInput').val("");
            $('#titleInput').val("");
            $('#phoneInput').val("");
            $('#mailInput').val("");
            $('#pwdInput').val("");
            $('#rePwdInput').val("");
            layer.open({
                id: 1,
                type: 1,
                title: '新建用户',
                skin: 'layui-layer-prompt',
                content: $("#CreatUserForm"),
                area: ["400px", "610px"],
                btn: ['保存', '取消'],
                shadeClose: false, //点击遮罩关闭
                btn2: function (index, layero) {
                    $('#ztreeDiv').hide();
                    layer.close(index);
                },
                btn1: function (index, layero) {
                    let insertType = false
                    $('#ztreeDiv').hide();
                    var inputData = {
                        userName: $('#userNameInput').val(),
                        name: $('#fullNameInput').val(),
                        // department: $('#orgInput').attr('checkid'),
                        department: $('#orgInputNew').val(),
                        title: $('#titleInput').val(),
                        phone: $('#phoneInput').val(),
                        mail: $('#mailInput').val(),
                        password: $('#pwdInput').val(),
                        rePassword: $('#rePwdInput').val(),
                        type: document.getElementById("isManagerInput").checked ? 1 : 0
                    };

                    if (!inputData.userName) {
                        layui.layer.msg('请输入用户名', {
                            shade: 0.3,
                            time: 1000 // 1秒关闭
                        });
                        return;
                    }
                    if (inputData.userName.length >= 15) {
                        layui.layer.msg('用户名长度在不能超过15 个字符', {
                            shade: 0.3,
                            time: 1000 // 1秒关闭
                        });
                        return;
                    }
                    $.ajax({
                        type: 'post',
                        async: false,
                        url: modelApi + 'user/isUserExist',
                        xhrFields: {
                            withCredentials: true
                        },
                        crossDomain: true,
                        data: {
                            userName: inputData.userName
                        },
                        datatype: 'json',
                        success: function (res) {
                            let data = JSON.parse(res)
                            if (data.code === 500) {
                                layui.layer.msg(data.msg, {
                                    shade: 0.3,
                                    time: 1000 // 1秒关闭
                                });
                                insertType = false
                            } else {
                                insertType = true
                            }
                        }
                    })
                    if (insertType) {
                        if (!inputData.name) {
                            layui.layer.msg('请输入中文名', {
                                shade: 0.3,
                                time: 1000 // 1秒关闭
                            });
                            return;
                        }
                        if (!inputData.department) {
                            layui.layer.msg('请选择所在部门', {
                                shade: 0.3,
                                time: 1000 // 1秒关闭
                            });
                            return;
                        }
                        if (!inputData.title) {
                            layui.layer.msg('请输入职务', {
                                shade: 0.3,
                                time: 1000 // 1秒关闭
                            });
                            return;
                        }
                        if (!inputData.phone) {
                            layui.layer.msg('请输入手机号码', {
                                shade: 0.3,
                                time: 1000 // 1秒关闭
                            });
                            return;
                        }
                        if (!inputData.password) {
                            layui.layer.msg('请输入密码', {
                                shade: 0.3,
                                time: 1000 // 1秒关闭
                            });
                            return;
                        }
                        if (inputData.password != inputData.rePassword) {
                            layui.layer.msg('请确认两次输入密码一致', {
                                shade: 0.3,
                                time: 1000 // 1秒关闭
                            });
                            return;
                        }
                        // 查看名字是否重复的ajax  
                        $.ajax({
                            type: 'post',
                            async: false,
                            url: modelApi + 'user/insertUser',
                            data: {
                                no: inputData.userName,
                                name: inputData.name,
                                pass: inputData.password,
                                fkDept: rootNodeId,
                                ismanager: inputData.type, // 是否为部门管理员
                                email: inputData.mail,
                                tel: inputData.phone,
                                fkDuty: inputData.title,
                                userName:inputData.userName
                            },
                            datatype: 'json',
                            success: function (res) {
                                layer.close(index);
                                layui.layer.msg('创建成功', {
                                    shade: 0.3,
                                    time: 1000 // 1秒关闭
                                });
                                getUserInfo(getUserHis[0], getUserHis[1], getUserHis[2]);
                            },
                            error: function (err) {
                                console.log(err);
                            }
                        })
                    }
                },
            });
            $('#userNameInput, #fullNameInput, #orgInput, #titleInput,#phoneInput,#mailInput,#pwdInput,#rePwdInput').on('blur', function () {
                if (!valueCheck.checkUnallowable(this.value)) {
                    this.value = '';
                    layui.layer.msg('请勿输入特殊字符或关键字', {
                        shade: 0.3,
                        time: 1000 // 1秒关闭
                    });
                }
            });
            $('#phoneInput').on('blur', function () {
                if (this.value && !valueCheck.checkPhone(this.value)) {
                    this.value = '';
                    layui.layer.msg('请输入正确的手机号', {
                        shade: 0.3,
                        time: 1000 // 1秒关闭
                    });
                }
            });
            // 手机号数字验证
            $('#phoneInput').on('input keyup', function () {
                this.value = this.value.replace(/[^\d]/g, '');
            });
            $('#mailInput').on('blur', function () {
                if (this.value && !valueCheck.checkMail(this.value)) {
                    this.value = '';
                    layui.layer.msg('请输入正确的邮箱', {
                        shade: 0.3,
                        time: 1000 // 1秒关闭
                    });
                }
            });

            // 点击选择部门
            // $('#orgInput').on('click', function () {
            //     if ($('#ztreeDiv').is(':hidden')) {
            //         var top = $('#orgInput').offset().top + $('#orgInput').height() + 3;
            //         var left = $('#orgInput').offset().left;
            //         $('#ztreeDiv').show().css({
            //             top: top,
            //             left: left
            //         });
            //     } else {
            //         $('#ztreeDiv').hide();
            //     }
            // });
            jQuery.fn.isChildOf = function (b) {
                return (this.parents(b).length > 0);
            };
            // $('#orgInput')[0].addEventListener('blur', function (e) {
            //     //若是由点击引起的焦点改变，捕获点击了的元素
            //     var ele = e.relatedTarget;
            //     // console.log(ele);
            //     if (!$(ele).isChildOf('#ztreeDiv')) {
            //         $('#ztreeDiv').hide();
            //     }
            // }, false);
        } else {
            layer.msg('请选择需要编辑的机构', {
                icon: 0
            });
        }
    });

    // 修改
    $('.editBtn').on('click', function () {
        if (addBranchType) {
            flag = "isEdit";
            var $this = $(this);
            if ($this.hasClass('unable')) {
                return;
            }
            var $td = $('#userTable .curSelectedNode td');
            var userId = $('#userTable .curSelectedNode').attr('userId');
            var html = `
            <div>
                <span>用户名：</span>
                <input id="userNameInput" type="text" class="layui-layer-input" autocomplete="new-password" maxlength="20" value="` + $td.eq(0).html() + `"><br>
                <span>中文名：</span>
                <input id="fullNameInput" type="text" class="layui-layer-input" autocomplete="new-password"  maxlength="20" value="` + $td.eq(1).html() + `"><br>
                <span>所在部门：</span>
                <input id="orgInput" type="text" class="layui-layer-input" autocomplete="new-password" readonly="readonly" checkid="` + $td.eq(2).attr('departmentId') + `" value="` + $td.eq(2).html() + `"><br>
                <span>职务：</span>
                <input id="titleInput" type="text" class="layui-layer-input" autocomplete="new-password" maxlength="20" value="` + $td.eq(3).html() + `"><br>
                <span>手机号码：</span>
                <input id="phoneInput" type="txt" class="layui-layer-input" autocomplete="new-password" maxlength="11" value="` + $td.eq(4).html() + `"><br>
                <span>邮箱：</span>
                <input id="mailInput" type="text" class="layui-layer-input" autocomplete="new-password" maxlength="100" value="` + $td.eq(5).html() + `"><br>
                <span>部门管理员：</span>
                <input id="typeInput" type="checkbox" ` + ($td.eq(6).html() == '是' ? 'checked' : '') + ` value="true"` + `><br>
            </div>`;


            $('#edituserNameInput').val($td.eq(0).html());
            $('#editfullNameInput').val($td.eq(1).html());
            $('#editorgInput').val($td.eq(2).html());
            $('#editorgInput').attr('checkid', $td.eq(2).attr('departmentId'));
            $('#edittitleInput').val($td.eq(3).html());
            $('#editphoneInput').val($td.eq(4).html());
            $('#editmailInput').val($td.eq(5).html());
            $('#typeInput').val("true");
            if ($td.eq(6).html() == '是') {
                $('#typeInput').attr('checked', '');
            }
            layui.form.render();
            layer.open({
                id: 2,
                type: 1,
                title: '修改用户信息',
                skin: 'layui-layer-prompt',
                content: $("#EditUserForm"),
                area: ["400px", "510px"],
                btn: ['保存', '取消'],
                shadeClose: false, //点击遮罩关闭
                btn2: function (index, layero) {
                    $('#ztreeDiv').hide();
                    layer.close(index);
                },
                btn1: function (index, layero) {
                    $('#ztreeDiv').hide();
                    var inputData = {
                        userName: $('#edituserNameInput').val(),
                        name: $('#editfullNameInput').val(),
                        department: $('#editorgInput').attr('checkid'),
                        title: $('#edittitleInput').val(),
                        phone: $('#editphoneInput').val(),
                        mail: $('#editmailInput').val(),
                        type: document.getElementById("typeInput").checked ? 1 : 0
                    };
                    if (!inputData.userName) {
                        layui.layer.msg('请输入用户名', {
                            shade: 0.3,
                            time: 1000 // 1秒关闭
                        });
                        return;
                    }
                    if (!inputData.name) {
                        layui.layer.msg('请输入中文名', {
                            shade: 0.3,
                            time: 1000 // 1秒关闭
                        });
                        return;
                    }
                    if (!inputData.department) {
                        layui.layer.msg('请选择所在部门', {
                            shade: 0.3,
                            time: 1000 // 1秒关闭
                        });
                        return;
                    }
                    if (!inputData.title) {
                        layui.layer.msg('请输入职务', {
                            shade: 0.3,
                            time: 1000 // 1秒关闭
                        });
                        return;
                    }
                    if (!inputData.phone) {
                        layui.layer.msg('请输入手机号码', {
                            shade: 0.3,
                            time: 1000 // 1秒关闭
                        });
                        return;
                    }
                    $.ajax({
                        type: 'post',
                        async: false,
                        // url: '/BaseAshx/User/UserManage.ashx', 
                        url: modelApi + 'user/updateUser',
                        // data: $.extend({}, inputData, {
                        //     mtype: 'UserManage_UpdateByManager',
                        //     userId: userId
                        // }),
                        data: {
                            userName: inputData.userName,
                            name: inputData.name,
                            pass: inputData.password,
                            fkDept: rootNodeId,
                            ismanager: inputData.type, // 是否为部门管理员
                            email: inputData.mail,
                            tel: inputData.phone,
                            fkDuty: inputData.title,
                            id: userId
                        },
                        datatype: 'json',
                        success: function (res) {
                            res = JSON.parse(res);
                            if (res.code == 200) {
                                layer.close(index);
                                layui.layer.msg(res.msg, {
                                    shade: 0.3,
                                    time: 1000 // 1秒关闭
                                });
                                getUserInfo(getUserHis[0], getUserHis[1], getUserHis[2])
                            } else {
                                layui.layer.msg(res.msg, {
                                    shade: 0.3,
                                    time: 1000 // 1秒关闭
                                });
                            }
                        },
                        error: function (err) {
                            console.log(err);
                        }
                    });
                },
            });
            $('#edituserNameInput, #editfullNameInput, #editorgInput, #edittitleInput,#editphoneInput,#editmailInput').on('blur', function () {
                if (!valueCheck.checkUnallowable(this.value)) {
                    this.value = '';
                    layui.layer.msg('请勿输入特殊字符或关键字', {
                        shade: 0.3,
                        time: 1000 // 1秒关闭
                    });
                }
            });
            $('#editphoneInput').on('blur', function () {
                if (this.value && !valueCheck.checkPhone(this.value)) {
                    this.value = '';
                    layui.layer.msg('请输入正确的手机号', {
                        shade: 0.3,
                        time: 1000 // 1秒关闭
                    });
                }
            });
            // 手机号数字验证
            $('#editphoneInput').on('input keyup', function () {
                this.value = this.value.replace(/[^\d]/g, '');
            });
            $('#editmailInput').on('blur', function () {
                if (this.value && !valueCheck.checkMail(this.value)) {
                    this.value = '';
                    layui.layer.msg('请输入正确的邮箱', {
                        shade: 0.3,
                        time: 1000 // 1秒关闭
                    });
                }
            });

            // 点击选择部门
            $('#editorgInput').on('click', function () {
                if ($('#ztreeDiv').is(':hidden')) {
                    var top = $('#editorgInput').offset().top + $('#editorgInput').height() + 3;
                    var left = $('#editorgInput').offset().left;
                    $('#ztreeDiv').show().css({
                        top: top,
                        left: left
                    });
                } else {
                    // console.log('隐藏');
                    // $('#ztreeDiv').hide();
                }
            });
            jQuery.fn.isChildOf = function (b) {
                return (this.parents(b).length > 0);
            };
            $('#editorgInput')[0].addEventListener('blur', function (e) {
                //若是由点击引起的焦点改变，捕获点击了的元素
                var ele = e.relatedTarget;
                console.log(ele);
                if (!$(ele).isChildOf('#ztreeDiv')) {
                    $('#ztreeDiv').hide();
                }
            }, false);
        } else {
            layer.msg('请选择需要编辑的用户', {
                icon: 0
            });
        }
    });

    // 删除
    $('.deleteBtn').on('click', function () {
        if (addBranchType) {
            var $this = $(this);
            if ($this.hasClass('unable')) {
                return;
            }
            var userId = $('#userTable .curSelectedNode').attr('userId');
            var $td = $('#userTable .curSelectedNode td');
            var userId = $('#userTable .curSelectedNode').attr('userId');
            console.log(userId, '$td');
            var content = '<div>\n' +
                '<a id="check">当前操作不可撤销, 确定删除当前所选用户吗?</a>\n' +
                '</div>';
            layer.open({
                id: 3,
                type: 1,
                title: '注意, 您正在执行删除操作',
                skin: 'layui-layer-prompt',
                content: content,
                btn: ['确定', '取消'],
                area: ['300px', '160px'],
                shadeClose: true, //点击遮罩关闭
                btn2: function (index, layero) {
                    layer.close(index);
                },
                btn1: function (index, layero) {

                    $.ajax({
                        type: 'post',
                        async: false,
                        // url: '/BaseAshx/User/UserManage.ashx', 
                        url: modelApi + 'user/deleteUser',
                        data: {
                            id: userId
                        },
                        datatype: 'json',
                        success: function (res) {
                            res = JSON.parse(res);
                            layer.close(index);
                            if (res.code == 200) {
                                layui.layer.msg(res.msg, {
                                    shade: 0.3,
                                    time: 1000 // 1秒关闭
                                });
                                getUserInfo(getUserHis[0], getUserHis[1], getUserHis[2])
                                // getUserInfo(nowNodeId, nowPage);
                            } else {
                                layui.layer.msg(res.msg, {
                                    shade: 0.3,
                                    time: 1000 // 1秒关闭
                                });
                            }
                            console.log(res);
                        },
                        error: function (error) {
                            console.log(error);
                        }
                    });
                },
                success: function () {
                    this.enterConfirm = function (event) {
                        if (event.keyCode === 13) {
                            $(".layui-layer-btn0").click();
                            return false; //阻止系统默认回车事件
                        }
                    };
                    $(document).on('keydown', this.enterConfirm); //监听键盘事件
                    // 点击确定按钮回调事件
                    $(".layui-layer-btn0").on("click", function () {
                        console.log("peace and love");
                    });
                },
                end: function () {
                    $(document).off('keydown', this.enterConfirm); //解除键盘事件
                }
            });
            $('.layui-layer-title').css({
                color: 'red',
            });
        } else {
            layer.msg('请选择需要删除的用户', {
                icon: 0
            });
        }
    });

    // 重置密码
    $('.resetPassWordBtn').on('click', function () {
        if (addBranchType) {
            var $this = $(this);
            if ($this.hasClass('unable')) {
                return;
            }
            var userId = $('#userTable .curSelectedNode').attr('userId');
            var $td = $('#userTable .curSelectedNode td');
            var html = '<input style="display:none">';
            html += '<span>' + '密码' + '：</span><input id="pwd1" type="password" class="layui-layer-input" autocomplete=“new-password” value=""> <br/>' + '<span>' + '确认密码' + '：</span><input id="repwd1" type="password" class="layui-layer-input" autocomplete="new-password" value=""><br/ >';
            var content = '<div>' + html + '</div>';

            layer.open({
                id: 4,
                type: 1,
                title: '重置用户密码',
                skin: 'layui-layer-prompt',
                content: content,
                btn: ['重置', '取消'],
                shadeClose: true, //点击遮罩关闭
                btn2: function (index, layero) {
                    layer.close(index);
                },
                btn1: function (index, layero) {
                    var pwd = $('#pwd1').val();
                    var rePwd = $('#repwd1').val();
                    if (!pwd) {
                        layui.layer.msg('请输入密码', {
                            shade: 0.3,
                            time: 1000 // 1秒关闭
                        });
                        return;
                    }
                    if (!rePwd) {
                        layui.layer.msg('请再次输入密码', {
                            shade: 0.3,
                            time: 1000 // 1秒关闭
                        });
                        return;
                    }
                    if (pwd != rePwd) {
                        layui.layer.msg('请确认两次输入密码一致', {
                            shade: 0.3,
                            time: 1000 // 1秒关闭
                        });
                        return;
                    }
                    $.ajax({
                        type: 'post',
                        async: false,
                        // url: '/BaseAshx/User/UserManage.ashx',
                        url: modelApi + 'user/updateUser',
                        data: {
                            id: userId,
                            pass: $('#pwd1').val()
                        },
                        datatype: 'json',
                        success: function (res) {
                            res = JSON.parse(res);
                            console.log(res);
                            if (res.code == 200) {
                                layer.close(index);
                                layui.layer.msg(res.msg, {
                                    shade: 0.3,
                                    time: 1000 // 1秒关闭
                                });
                            } else {
                                layui.layer.msg(res.msg, {
                                    shade: 0.3,
                                    time: 1000 // 1秒关闭
                                });
                            }
                        },
                        error: function (err) {
                            console.log(err);
                        }
                    });
                },
            });
        } else {
            layer.msg('请选择需要重置密码的用户', {
                icon: 0
            });
        }
    });

    var settingLeft = {
        view: {
            dblClickExpand: false, //双击节点时，是否自动展开父节点的标识
            showLine: false, //是否显示节点之间的连线
            showIcon: true,
            fontCss: {
                //'color': 'white',
                'font-weight': 'normal'
            }, //字体样式函数
            selectedMulti: false //设置是否允许同时选中多个节点
        },
        check: {
            //chkboxType: { "Y": "ps", "N": "ps" },
            chkStyle: "checkbox", //复选框类型
            enable: false //每个节点上是否显示 CheckBox
        },
        data: {
            simpleData: { //简单数据模式
                enable: true,
                idKey: "id",
                pIdKey: "pId",
                rootPId: ""
            }
        },
        callback: {
            onClick: function (event, treeId, treeNode) {
                zTree = $.fn.zTree.getZTreeObj("menu_tree_left");
                if ($(event.target).hasClass('ico_close') || $(event.target).hasClass('ico_open')) {
                    zTree.expandNode(treeNode); //如果是父节点，则展开该节点
                }
                var text = $(event.target).text();
                // console.log(treeNode);
                if (text) {
                    if (flag == "isAdd") {
                        $('#orgInput').attr('checkId', treeNode.id);
                        $('#orgInput').val(text);
                    } else {
                        $('#editorgInput').attr('checkId', treeNode.id);
                        $('#editorgInput').val(text);
                    }
                    $('#ztreeDiv').hide();
                }
            },
        }
    };

    // 获取左侧机构组织数据
    var zNodes;
    // 获取机构上下级树
    var orgData = [];

    function getDataAllDept() {
        $.ajax({
            type: "post",
            async: false,
            // url: "/BaseAshx/Org/OrgAshx.ashx", 
            url: modelApi + 'dept/getAllDepts',
            data: {
                // stype: 'OrgManage_QueryOrgTree',
                orgid: rootNodeId,
                treetype: 'down'
            },
            datatype: "json",
            success: function (result) {
                // console.log(result);
                result = JSON.parse(result);
                if (result.code == 200) {
                    var data = result.data;
                    zNodes = data.map(function (item, index) {
                        // console.log(item);
                        var mapResult = {
                            "id": item.ORG_ID,
                            "name": item.ORGSHORTNAME,
                            "pId": item.ORG_PID,
                        };
                        if (index == 0) {
                            mapResult.open = true;
                        }
                        return mapResult;
                    });
                    //初始化菜单树
                    $.fn.zTree.init($("#menu_tree_left"), settingLeft, zNodes);
                    // 点击第一个节点,获取右侧数据
                    // setTimeout(function () {
                    //     $('#menu_tree_left2 a').eq(0).click();
                    // }, 100);
                } else {
                    layui.layer.msg('获取机构数据错误,请稍候再试', {
                        shade: 0.3,
                        time: 1000 // 1秒关闭
                    });
                }
            },
            error: function (error) {
                console.log(error);
            }
        });
    }
    getDataAllDept()
    var settingLeft2 = {
        view: {
            showTitle: false,
            dblClickExpand: false, //双击节点时，是否自动展开父节点的标识
            showLine: false, //是否显示节点之间的连线
            showIcon: true,
            fontCss: {
                //'color': 'white',
                'font-weight': 'normal'
            }, //字体样式函数
            selectedMulti: false //设置是否允许同时选中多个节点
        },
        check: {
            //chkboxType: { "Y": "ps", "N": "ps" },
            chkStyle: "checkbox", //复选框类型
            enable: false //每个节点上是否显示 CheckBox
        },
        data: {
            simpleData: { //简单数据模式
                enable: true,
                idKey: "id",
                pIdKey: "pId",
                rootPId: ""
            }
        },
        callback: {
            beforeClick: function (treeId, treeNode) {
                zTree = $.fn.zTree.getZTreeObj("menu_tree_left");
                if (zTree) {
                    $('.addBtn').removeClass('unable')
                    addBranchType = true 
                    adType = true 
                }
                // if (!treeNode.isParent) {
                //     zTree.checkNode(treeNode, !treeNode.checked, true, true); //单击勾选，再次单击取消勾选
                // }

                // if ($(event.target).hasClass('ico_close') || $(event.target).hasClass('ico_open')) {
                //     zTree.expandNode(treeNode); //如果是父节点，则展开该节点
                // }
            },

            onClick: function (event, treeId, treeNode, e) {
                $('.editBtn, .deleteBtn, .resetPassWordBtn').addClass('unable');
                zTree = $.fn.zTree.getZTreeObj("menu_tree_left2");
                if ($(event.target).hasClass('ico_close') || $(event.target).hasClass('ico_open')) {
                    zTree.expandNode(treeNode); //如果是父节点，则展开该节点
                }
                var text = $(event.target).text();
                orgInputNewText = text
                rootNodeId = Number(treeNode.id)
                // 获取右侧对应用户数据
                nowNodeId = treeNode.id;
                nowNode = treeNode;
                $('#pagination').html('');
                getUserInfo(nowNodeId);
                // if (text) {
                //     $('#orgInput').val(text);
                //     $('#ztreeDiv').hide();
                // }
            },
            onDblClick: function (treeId, treeNode) {
                //code
            }
        }
    };
    $.fn.zTree.init($("#menu_tree_left2"), settingLeft2, zNodes);

    var valueCheck = {
        // 检测非法字符,防止SQL注入
        checkUnallowable: function (value) {
            var re = /select|update|delete|exec|count|’|"|=|;|>|<|%/i;
            if (re.test(value)) {
                return false;
            } else {
                return true;
            }
        },
        // 检测手机号格式
        checkPhone: function (phone) {
            if ((/^1(3|4|5|6|7|8|9)\d{9}$/.test(phone))) {
                return true;
            } else {
                return false;
            }
        },
        checkMail: function (mail) {
            // var red = /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/';
            var reg = /^[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*@[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*\.[a-z]{2,}$/;
            if ((reg.test(mail))) {
                return true;
            } else {
                return false;
            }
        }
    }
});